<template>
    <div class="my-container" id="c">
        <div class="my-header">
            <a-tabs   :lazy-load="true">
                <a-tab-pane title="角色列表">
                    <div class="search-form" v-if="headerShow">
                        <a-form size="small" layout="inline" :model="searchParams">
                            <a-form-item label="角色名称">
                                <a-select popup-container="html"  :style="{ width: '150px' }" :loading="loading"
                                    :allowClear="true" :filter-option="false" allow-search
                                    v-model="searchParams.roleName" @search="handleSearch" @focus="focusSel">
                                    <a-option v-for="item in searchParams.roleNameList" :value="item['roleName']">
                                        {{ item['roleName'] }}
                                    </a-option>
                                </a-select>
                            </a-form-item>
                        </a-form>
                    </div>
                    <div class="my-divisders">
                        <a-divider orientation="center">
                            <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                            <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                        </a-divider>
                    </div>
                    <div class="my-tool-bar">
                        <ToolBar @add="addHandler" :style="{ marginRight: '20px' }" @select="doRefresh"
                            @open="headerShow = true" @del="deleteHandler" @close="headerShow = false"
                            :items="['查询', '新增', '删除']"></ToolBar>
                    </div>
                </a-tab-pane>
            </a-tabs>
        </div>
        <div class="split-bar">

        </div>
        <div class="my-body" :style="{ height: headerShow ? '80%' : 'calc(80% + 40px)' }">
            <a-table @page-change="pagination.change" size="small" :pagination="true" :scrollbar="true"
                v-model:selected-keys="selectedRowKeys" :row-selection="rowSelection" :columns="column"
                :loading="table.loading" :data="table.dataList" :row-key="rowKey" :scroll="{ x: '100%', y: '100%' }"
                :bordered="{ wrapper: true, cell: true, headerCell: true }" stripe sticky-header>
                <template #action="{ record }">
                    <a-space>
                        <a-tag @click="editHandler(record)" type="primary" status="warning" size="small">
                            <template #icon>
                                <icon-edit></icon-edit>
                            </template>
                            修改
                        </a-tag>
                        <a-tag @click="editRolesHandler(record)" type="primary" status="danger" size="small">
                            <template #icon>
                                <icon-edit></icon-edit>
                            </template>
                            编辑权限
                        </a-tag>
                    </a-space>
                </template>
            </a-table>
        </div>
        <a-drawer ok-text='保存' cancel-text='关闭' :style="{ zIndex: '999' }" :width="400" popup-container="#c"
            :visible="showSide" @cancel="showSide = false" :mask-closable="false" @ok="sideOk" :ok-loading="sideLoding">
            <template #title> {{ sideTitle }}</template>
            <a-form ref="formRef" layout="vertical" :model="dataForm" field="roleCode">
                <a-form-item label="角色编号"
                    :rules="[{ required: true, message: '编号必填' }, { match: /^[a-zA-Z0-9]{1,}$/g, message: '编号必须是数字和字母' }]"
                    :validate-trigger="['change', 'blur']">
                    <a-input @blur="dataForm.roleCode = dataForm.roleCode.toUpperCase()" v-model="dataForm.roleCode"
                        placeholder=""></a-input>
                </a-form-item>
                <a-form-item label="角色名" field="roleName" :rules="[{ required: true, message: '角色名必填' }]"
                    :validate-trigger="['change', 'blur']">
                    <a-input v-model="dataForm.roleName" placeholder=""></a-input>
                </a-form-item>
                <a-form-item label="备注" field="remark">
                    <a-input v-model="dataForm.remark" ></a-input>
                </a-form-item>
            </a-form>
        </a-drawer>
        <a-modal @ok="rok"  @cancel="setRoleData.show = false" :visible="setRoleData.show" title="角色权限设置">
            <a-scrollbar style="height:500px;overflow:auto">
                <a-tree  v-model:expanded-keys="zk" default-expand-all  ref="roletree" :data="data1" v-model:checked-keys="rowlist" checkable show-line>
                </a-tree>
            </a-scrollbar>

        </a-modal>
    </div>

</template>
<script lang="ts">
import { reactive, toRefs, onMounted, ref } from 'vue';

import { useRowKey, useTable, useRowSelection, usePagination, useTableColumn } from '@/hooks/table'
import ToolBar from '@/components/Toolbar.vue'
import { del, get, post, put } from '@/api/http'
import { FormInstance, Message, Modal, TreeInstance } from '@arco-design/web-vue';
import emitter from "@/hooks/useEventBus";



interface Role {
    "id": number | string
    "roleName": string
    "roleCode": string
    "remark": string
    "deleteState": boolean,
}

export default {
    name: 'Roles',
    components: {
        ToolBar
    },

    setup() {
        const data1 = ref<any[]>([])
        onMounted(() => {
            // emitter.on("refresh-Roles", () => doRefresh());
            emitter.on("refresh-Roles", () => {
                get({
                    url: 'admin/acl/permission/indexAllPermission'
                }).then(({ code, data }) => {
                    if (code === 200) {
                        data1.value = data.children.map(function (o: any) {
                            let temp1 = { title: o.name, key: o.id }
                            temp1['children'] = Array.isArray(o.children) ? o.children.map((o1: any) => {
                                let temp2 = { title: o1.name, key: o1.id }
                                temp2['children'] = Array.isArray(o1.children) ? o1.children.map((o2: any) => {
                                    let temp3 = { title: o2.name, key: o2.id }
                                   
                                    temp3['children'] = Array.isArray(o2.children) ? o2.children.map((o3: any) => {
                                        let temp4 = { title: o3.name, key: o3.id }
                                        temp4['children'] = Array.isArray(o3.children) ? o3.children.map((o4: any) => {
                                            let temp5 = { title: o4.name, key: o4.id }
                                            return temp5
                                        }) : []
                                        return temp4
                                    }) : []
                                    return temp3
                                }) : []
                                return temp2
                            }) : []
                            return temp1
                        })

                    } else {
                        Message.error('获取菜单失败！')
                    }
                })
                doRefresh();
            });

        })
        const headerShow = ref<boolean>(true)
        const doRefresh = () => {
            tableData.table.loading = true
            get({
                url: 'admin/acl/role/index',
                data: {
                    page: tableData.pagination.page,
                    limit: 20,
                    roleName: pageData.searchParams.roleName
                }
            }).then((res) => {
                tableData.table.handleSuccess(res.data.items)

                tableData.pagination.setTotalSize(res.data.total)

            }).finally(() => {
                tableData.table.loading = false
            })
        }
        const pageData = reactive<{
            searchParams: {
                roleName: string,
                roleNameList: []
            },
            showSide: boolean,
            sideTitle: string,
            sideLoding: boolean
        }>
            ({
                showSide: false,
                sideTitle: '新增菜单',
                searchParams: {
                    roleName: '',
                    roleNameList: []
                },
                sideLoding: false
            })
        const tableData = reactive<{ selectedRowKeys: any[], table: any, pagination: any, rowKey: any, rowSelection: any, column: any, rowData: any[] }>({
            rowData: [],
            table: useTable(),
            pagination: usePagination(doRefresh),
            rowKey: useRowKey('id'),
            rowSelection: useRowSelection(),
            selectedRowKeys: [],
            column: useTableColumn([{
                title: '角色编号',
                key: 'roleCode',
                dataIndex: 'roleCode',
                width: 100
            }, {
                title: '角色名',
                key: 'roleName',
                dataIndex: 'roleName'

            }, {
                title: '备注',
                key: 'remark',
                dataIndex: 'remark'
            }, {
                title: '修改时间',
                dataIndex: 'gmtModified',
                key: 'gmtModified'
            }, {
                title: '操作',
                key: 'id',
                fixed: 'right',
                slotName: 'action',
                width: 300
            }])
        })
        const dataForm = reactive<Role>({
            id: "",
            remark: "",
            roleCode: '',
            roleName: "",
            deleteState: false
        })
        const addHandler = () => {
            
            Object.keys(dataForm).forEach((o) => dataForm[o] = undefined)
            pageData.sideTitle = '新增角色'
            pageData.showSide = true
        }


        const deleteHandler = () => {

            if (tableData.selectedRowKeys.length === 0) {
                return;
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {

                    del({
                        url: "admin/acl/role/batchRemove/" + tableData.selectedRowKeys.join(','),
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            tableData.pagination.page = 1
                            doRefresh();
                        } else {
                            Message.error({
                                content: "删除失败",
                                duration: 5000,
                            });
                        }

                    });
                },
            });
        };
        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {

                    pageData.sideLoding = true
                    if (pageData.sideTitle === '新增角色') {
                        post({
                            url: 'admin/acl/role/save',
                            data: {
                                deleteState: false,
                                roleCode: dataForm.roleCode,
                                roleName: dataForm.roleName,
                                remark: dataForm.remark
                            }
                        }).then((res) => {
                            if (res.code === 200) {
                                Message.success('新增成功')
                                pageData.showSide = false
                                doRefresh()
                            } else {
                                Message.error(res['message'] || '新增失败')
                            }
                        }).finally(() => {
                            pageData.sideLoding = false
                        })

                    } else {

                        put({
                            url: 'admin/acl/role/update',
                            data: {
                                deleteState: false,
                                roleCode: dataForm.roleCode,
                                roleName: dataForm.roleName,
                                id: dataForm.id,
                                remark: dataForm.remark
                            }
                        }).then((res) => {
                            if (res.code === 200) {
                                Message.success('修改成功')
                                pageData.showSide = false
                                doRefresh()
                            } else {
                                Message.error(res['message'] || '修改失败')
                            }
                        }).finally(() => {
                            pageData.sideLoding = false
                        })
                    }
                }
            })
        }
        const editHandler = (record: Role) => {
            Object.keys(dataForm).forEach(o => dataForm[o] = record[o])
            pageData.sideTitle = '修改角色'
            pageData.showSide = true
        }
        const roletree = ref<TreeInstance>()
        const rowlist = ref<any[]>([])

        const zk = ref<any>([])
        let roid = ''
        const editRolesHandler = (record: Role) => {

            get({
                url: 'admin/acl/permission/toAssign/' + record.id
            }).then(({ code, data }) => {
                if (code === 200) {
                    rowlist.value = []
                    data.children.forEach(function (o: any) {
                        zk.value.push(o.id)
                        if (Array.isArray(o.children) && o.children.length > 0) {
                            o.children.forEach((o1: any) => {
                                zk.value.push(o1.id)
                                if (Array.isArray(o1.children) && o1.children.length > 0) {
                                    o1.children.forEach((o2: any) => {
                                        if (Array.isArray(o2.children) && o2.children.length > 0) {
                                            o2.children.forEach((o3: any) => {
                                                if (Array.isArray(o3.children) && o3.children.length >0) {
                                                    o3.children.forEach((o4: any) => {
                                                        if (Array.isArray(o4.children) && o4.children.length >0) {
                                                            o4.children.forEach((o5: any) => {
                                                                if(o5.select)
                                                                rowlist.value.push(o5.id)
                                                            })
                                                        } else {
                                                            if(o4.select)
                                                            rowlist.value.push(o4.id)
                                                        }
                                                    })
                                                } else {
                                                    if(o3.select)
                                                    rowlist.value.push(o3.id)
                                                }

                                            })
                                        } else {
                                            if(o2.select)
                                            rowlist.value.push(o2.id)
                                        }
                                    })
                                } else {
                                    if(o1.select)
                                    rowlist.value.push(o1.id)
                                }
                            })
                        } else {
                            if(o.select)
                            rowlist.value.push(o.id)
                        }

                    })
                    roid = record.id + ''

                    setRoleData.show = true
                } else {
                    rowlist.value.length = 0
                    Message.error('获取角色权限失败')
                }
            })
        }
        const rok = ()=>{
          post({
            url:'/admin/acl/permission/doAssign?roleId=' + roid,
            data:rowlist.value
          }).then(({code,data})=>{
            if(code === 200){
                Message.success('设置成功')
                setRoleData.show = false
            }else{
                Message.success('设置失败')
            }
          })
        }
        //下拉框得到焦点
        const focusSel = () => {
            selRoleName({
                page: 1,
                limit: 30
            });
        }
        //下拉数据
        const options = ref<any>(pageData.searchParams.roleNameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = {
                    page: 1,
                    limit: 30,
                    roleName: value
                }
                loading.value = true;
                // 角色下拉框查询
                selRoleName(ob);
                options.value = pageData.searchParams.roleNameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };

        //角色下拉框查询
        function selRoleName(val: any) {
            get({
                url: "admin/acl/role/index",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.searchParams.roleNameList = data.items;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        // 设置权限的弹窗
        const setRoleData = reactive({
            show: false
        })
      
        return {
            zk,
            rok,
            roletree,
            rowlist,
            data1,
            loading,
            setRoleData,
            editRolesHandler,
            editHandler,
            sideOk,
            dataForm,
            formRef,
            addHandler,
            ...toRefs(pageData),
            ...toRefs(tableData),
            doRefresh,
            headerShow,
            handleSearch,
            focusSel,
            deleteHandler
        }
    }
}
</script>
<style scoped lang="less">
.my-container {
    height: 100%;
    min-height: 500px;
    max-height: 90%;
    width: 100%;
    max-height: 100%;

    &>.my-header {
        width: 100%;
        padding: 10px;
        padding-top: 0;
        background-color: white;


        min-height: 10%;

        &>.my-tool-bar {
            text-align: right;
        }
    }

    &>.my-body {
        width: 100%;
        padding: 10px;
        background-color: white;
        height: 85%;
        max-height: calc(85% + 40px);

    }

    &>.split-bar {
        height: 10px;
        width: 100%;
    }
}
</style>